package com.facebook.app.client.uiElements;

import com.facebook.app.shared.clustering.Cluster;
import com.facebook.app.shared.clustering.Clusterable;
import com.facebook.app.shared.facebookData.FacebookFriend;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionModel;
import com.google.gwt.view.client.TreeViewModel;

public class HierarchicalTreeModel implements TreeViewModel {

	private final SelectionModel<Clusterable> selectionModel;
	private final DefaultSelectionEventManager<Clusterable> selectionManager = DefaultSelectionEventManager.createCheckboxManager();
	private final Cell<Clusterable> cell;
	private final Clusterable root;
	
	public HierarchicalTreeModel(Clusterable root, SelectionModel<Clusterable> selectionModel, Cell<Clusterable> cell) {
		this.root = root;
		this.selectionModel = selectionModel;
		this.cell = cell;
	}
	
	@Override
	public <T> NodeInfo<?> getNodeInfo(T value) {
		
		if (value == null) {
			
			ListDataProvider<Clusterable> dataProvider = new ListDataProvider<Clusterable>();
			dataProvider.getList().add(root);
			
			if (root instanceof FacebookFriend) {
				return new DefaultNodeInfo<Clusterable>(dataProvider, cell, selectionModel, selectionManager, null);
			} else {
				return new DefaultNodeInfo<Clusterable>(dataProvider, cell);
			}
		} else if (value instanceof Cluster) {
			
			ListDataProvider<Clusterable> dataProvider = new ListDataProvider<Clusterable>();
			Cluster cluster = (Cluster) value;
			
			dataProvider.getList().add(cluster.getLeftChild());
			dataProvider.getList().add(cluster.getRightChild());
			
			return new DefaultNodeInfo<Clusterable>(dataProvider, cell, selectionModel, selectionManager, null);
		}
		
		throw new IllegalArgumentException("Unsupported object type: " + value.getClass().getName());
	}
	
	@Override
	public boolean isLeaf(Object value) {
		return value instanceof FacebookFriend;
	}

}
